package com.yuuko.yuukoapi.project.system.controller

import com.yuuko.yuukoapi.common.response.AjaxResult
import com.yuuko.yuukoapi.common.response.None
import com.yuuko.yuukoapi.model.system.Depts
import com.yuuko.yuukoapi.model.system.dto.DeptsUpdateInput
import com.yuuko.yuukoapi.repository.system.DeptsRepository
import org.babyfish.jimmer.sql.ast.mutation.SaveMode
import org.springframework.web.bind.annotation.DeleteMapping
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.PutMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

@RestController
@RequestMapping("/system/dept")
class DeptsController(
    val deptsRepository: DeptsRepository
) {

    @GetMapping("/list")
    fun getDeptList(): AjaxResult<List<Depts>> {
        val result = deptsRepository.findAllTree()
        return AjaxResult.ok(result)
    }

    @PostMapping
    fun createDept(@RequestBody input: DeptsUpdateInput): AjaxResult<None?> {
        deptsRepository.save(input, SaveMode.INSERT_ONLY)
        return AjaxResult.ok()
    }

    @PutMapping("/{id}")
    fun updateDept(@PathVariable id: String, @RequestBody input: DeptsUpdateInput): AjaxResult<None?> {
        deptsRepository.save(
            input.toEntity { this.id = id },
            SaveMode.UPDATE_ONLY
        )
        return AjaxResult.ok()
    }

    @DeleteMapping("/{id}")
    fun deleteDept(@PathVariable id: String): AjaxResult<None?> {
        deptsRepository.deleteById(id)
        return AjaxResult.ok()
    }


}